<template>
  <div class="blog-detail-container">
    <Layout>
      <div class="container" ref="container">
        <h1 class="title">{{ detailData.title }}</h1>
        <div class="aside">
          <span>日期：{{ formDate(detailData.createDate) }}</span>
          <span>浏览：{{ detailData.scanNumber }}</span>
          <a href="#blog-table-container">评论数：{{ detailData.commentNumber }}</a>
          <router-link :to="`/article/cata/${detailData?.category?.id}`"
            >分类：{{ detailData.category?.name }}</router-link
          >
        </div>
        <div
          ref="toastuiContainer"
          class="toastui-editor-contents"
          v-html="detailData.htmlContent"
        ></div>
        <div class="message-container">
          <DataForm :handleSubmit="handleSubmit"></DataForm>
          <DataLists title="评论列表" :data="detailComment" />
          <div class="loading" v-if="detailComment.rows?.length">
            <Loading v-if="isLoading" :imageUrl="loadSrc"></Loading>
            <h2 v-else>暂无更多数据</h2>
          </div>
          <Empty
            v-if="!detailComment.rows?.length"
            :title="emptyContent.title"
            :content="emptyContent.content"
          />
        </div>
      </div>
      <template #right>
        <div class="detail-toc" ref="tocContainer">
          <Toc
            :list="detailData.toc"
            :handleClick="handleClick"
            :handleScroll="handleScroll"
          />
        </div>
      </template>
    </Layout>
  </div>
</template>

<script setup>
import Layout from "@/Layouts/index.vue";
import DataForm from "@/components/MessageArea/DataForm.vue";
import DataLists from "@/components/MessageArea/DataLists.vue";
import Empty from "@/components/Empty/index.vue";
import Loading from "@/components/Loading/index.vue";
import Toc from "./components/Toc.vue";
import loadSrc from "@/assets/loading.svg";
import { getByBlogId } from "@/api/blog.js";
import {
  ref,
  onBeforeMount,
  onMounted,
  reactive,
  watch,
  computed,
  onBeforeUnmount,
} from "vue";
import { formDate } from "@/utils/tools.js";
import { useRoute } from "vue-router";
import { getByCategoryIdMessage, addCategoryIdComment } from "@/api/blog.js";
import Scroll from "@/composition/Scroll.js";

const toastuiContainer = ref(null);
const detailData = ref({});
const route = useRoute();
const container = ref(null);
const detailComment = ref({});
const total = ref(0);
const isLoading = ref(false);
const commentObj = reactive({
  page: 1,
  limit: 5,
});
const emptyContent = reactive({
  title: "等待佳音，静待君来",
  content:
    "乍一见面，不知你我瓦解情结，听取各位不偏不倚、独具匠心的神来之笔，我们受益匪浅，如沐春风。陈词滥调未苏醒前，昨晚星影依稀，诵读琴心剑气，点燃诗心火炬，要说您评价的文字，妙笔生花，从中回味处，人生百味尽在其中。",
});

Scroll(container);

// 评论提交
async function handleSubmit(dataForms) {
  await addCategoryIdComment({
    ...dataForms,
    blogId: `${detailData.value.id}`,
  });
  fetchData();
}

// 评论数据请求
async function fetchData() {
  isLoading.value = true;
  const res = await getByCategoryIdMessage({
    page: commentObj.page,
    limit: commentObj.limit,
    blogid: detailData.value.id,
  });
  if (commentObj.page !== 1) {
    detailComment.value.rows = [...detailComment.value.rows, ...res.rows];
  } else {
    detailComment.value = res;
    total.value = Math.ceil(res.total / commentObj.limit);
    if (total.value === 1) {
      isLoading.value = false;
    }
  }
}

function handleClick(item) {
  location.hash = item.anchor;
}

function handleScroll(newScroll) {
  container.value.addEventListener("scroll", newScroll);
}

// 监听的page的内容
watch(
  () => commentObj.page,
  () => {
    setTimeout(async () => {
      await fetchData();
      isLoading.value = false;
    }, 1000);
  }
);

// 创建滚动事件
onMounted(() => {
  container.value.addEventListener("scroll", handScroll);
  handleScroll();
});

// 销毁事件
onBeforeUnmount(() => {
  container.value.removeEventListener("scroll", handScroll);
});

// 绑定滚动事件
function handScroll() {
  if (
    container.value.scrollTop + container.value.offsetHeight + 10 >=
    container.value.scrollHeight
  ) {
    if (commentObj.page === total.value) {
      return;
    }
    commentObj.page++;
  }
}

//初始化请求数据
onBeforeMount(async () => {
  const id = route.params.id;
  const res = await getByBlogId(id);
  res.toc = JSON.parse(res.toc);
  detailData.value = res;
  fetchData();
});
</script>

<style lang="less" scoped>
@import url("@/style/toastui-editor.css");
@import url("@/style/var.less");

.blog-detail-container {
  width: 100%;
  height: 100%;
  position: relative;

  .container {
    width: 100%;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
    scroll-behavior: smooth;
    overflow: auto;

    .aside {
      color: @gray;
      font-size: 15px;

      span,
      a {
        margin-right: 5px;
      }
    }
  }

  .detail-toc {
    padding: 20px;
    box-sizing: border-box;
    width: 300px;
    height: 100%;
    overflow: auto;
  }
}

.loading {
  width: 100%;
  position: relative;
  height: 70px;

  h2 {
    text-align: center;
    color: @gray;
    font-size: 15px;
  }
}

.title {
  font-weight: bold;
  margin: 20px 0;
  font-size: 33px;
  color: @words;
}
</style>
